<template>
  <div class="back-button">
    <el-button type="primary" :icon="ArrowLeft" @click="$router.go(-1)">返回</el-button>
  </div>
  <div class="my-documents">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>我上传的文档</span>
          <el-upload class="upload-demo" :action="uploadUrl" :headers="headers" :on-success="handleSuccess"
            :on-error="handleError" :before-upload="beforeUpload" :file-list="fileList" accept=".doc,.docx,.pdf,.txt"
            :show-file-list="true" multiple>
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持 doc, docx, pdf, txt 格式文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </div>
      </template>

      <el-table :data="documents.filter(doc => doc.type === 'file')" style="width: 100%">
        <el-table-column label="文档名称">
          <template #default="scope">
            <a :href="scope.row.url" target="_blank" @click.prevent="handleArticleClick(scope.row.content)">{{
              scope.row.originalName }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="180"></el-table-column>
        <el-table-column prop="createTime" label="上传日期" width="180"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- <el-button @click="handleDownload(scope.row)" type="text" size="small">下载</el-button> -->
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>我生成的文档</span>
        </div>
      </template>
      <el-table :data="documents.filter(doc => doc.type === 'essay')" style="width: 100%">
        <el-table-column label="文档名称">
          <template #default="scope">
            <a href="#" @click.prevent="handleArticleClick(scope.row)">{{
              scope.row.title }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="180"></el-table-column>
        <el-table-column prop="createTime" label="上传日期" width="180"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- <el-button @click="handleDownload(scope.row)" type="text" size="small">下载</el-button> -->
            <el-button @click="handleDeleteEssay(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import { listEssay, getEssay, delEssay } from '@/api/essay'
import { listFiles, deleteFile } from '@/api/file'
import useUserStore from '@/store/modules/user'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const userId = userStore.id

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/system/file/upload'
const headers = ref({
  Authorization: 'Bearer ' + getToken()
})

const documents = ref([])  // 用于存放文件和文章的数据
const fileList = ref([])  // 用于上传的文件列表

const router = useRouter()

// 获取文件列表
const getFiles = async () => {
  try {
    const res = await listFiles()
    documents.value = res.rows.map(doc => ({ ...doc, type: 'file' })) || []
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败')
  }
}

// 获取文章列表
const getEssays = async () => {
  try {
    const res = await listEssay(userId)
    const essays = res.rows.map(essay => ({ ...essay, type: 'essay' })) || []
    documents.value = [...documents.value, ...essays]
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  }
}

// 上传前验证
const beforeUpload = (file) => {
  const allowTypes = ['.doc', '.docx', '.pdf', '.txt']
  const extension = '.' + file.name.split('.').pop().toLowerCase()
  const isValidType = allowTypes.includes(extension)
  if (!isValidType) {
    ElMessage.error('只能上传Word、PDF和TXT格式的文件!')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传成功
const handleSuccess = (response, file) => {
  if (response.code === 200) {
    ElMessage.success('上传成功')
    getFiles() // 刷新文件列表
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败
const handleError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('文件上传失败')
}

// 删除文件
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该文件吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteFile(row.fileId)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getFiles() // 刷新文件列表
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('文件删除失败')
    }
  })
}

// 删除生成文档
const handleDeleteEssay = async (row) => {
  ElMessageBox.confirm('确认要删除该文档吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await delEssay(row.essayId); // 使用对应的 essayId 删除
      if (res.code === 200) {
        ElMessage.success('删除成功');
        getEssays(); // 刷新文章列表
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('文档删除失败');
    }
  });
}

// 处理文章点击事件
const handleArticleClick = async (article) => {
  console.log(article.content); // 打印获取到的内容
  const res = await getEssay(article.essayId)
  console.log(res)

  router.push({
    name: 'Quill',
    query: {
      generatedPaper: res.data.content,
      fontSize: res.data.fontSize,
      indentation: res.data.indentation,
      headingSize: res.data.headingSize,
      lineHeight: res.data.lineHeight
    }
  });
}

// 在组件挂载时获取文件和文章列表
onMounted(() => {
  getFiles()
  getEssays()
})
</script>

<style scoped>
.back-button {
  margin: 20px 0 0 20px;
}

.my-documents {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-demo {
  margin-left: 16px;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}
</style>
